package com.tgky.ybzb.config.jwt;

import com.tgky.ybzb.config.exception.YBGLBaesException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.tgky.ybzb.constant.ResultConstant.NO_AUTH_401;

@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {


        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
//            chain.doFilter(request, response);
        }


        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            //jwt为空，抛出异常（这里我使用自定义异常了）
            throw new YBGLBaesException(NO_AUTH_401, "token为空");
        }
        try {
            JwtUtil.verify(token);
        } catch (Exception e) {
            //token验证失败或到这里抛出token无效异常
            throw new YBGLBaesException(NO_AUTH_401, "token无效异常");
        }
        return true;
    }
}